<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="规则编码" prop="ruleCode">
        <el-input
          v-model="queryParams.ruleCode"
          placeholder="请输入规则编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规则名称" prop="ruleName">
        <el-input
          v-model="queryParams.ruleName"
          placeholder="请输入规则名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="启用状态" prop="enableFlag">
        <el-select
          v-model="queryParams.enableFlag"
          placeholder="启用状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['md:rule:add']"
        >新增
        </el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleDYTM"
          v-hasPermi="['md:rule:add']"
        >打印
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ruleList">
      <el-table-column label="规则编码" align="center" prop="ruleCode"/>
      <el-table-column label="规则名称" align="center" prop="ruleName"/>
      <el-table-column label="启用/禁用" align="center" prop="enableFlag">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enableFlag"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="Y"
            inactive-value="N"
            @change="switchChange(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy"/>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" align="center" prop="updateBy"/>
      <el-table-column label="更新时间" align="center" prop="updateTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['md:rule:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['md:rule:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!--    新增/修改条码规则对话框-->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="规则编号" prop="ruleCode">
              <el-input v-model="form.ruleCode" placeholder="请输入规则编号" :readonly="optType != 'add'"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规则名称" prop="ruleName">
              <el-input v-model="form.ruleName" placeholder="请输入规则名称"/>
            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item label="描述" prop="ruleDesc">
          <el-input v-model="form.ruleDesc" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="最大长度" prop="maxLength">
              <el-input-number v-model="form.maxLength" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否启用" prop="enableFlag">
              <el-radio-group v-model="form.enableFlag">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否补齐" prop="isPadded">
              <el-radio-group v-model="form.isPadded">
                <el-radio label="Y">是</el-radio>
                <el-radio label="N">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.isPadded == 'Y'">
          <el-col :span="12">
            <el-form-item label="补齐字符" prop="paddedChar">
              <el-input v-model="form.paddedChar" placeholder="请输入补齐字符"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="补齐方式" prop="paddedMethod">
              <el-radio-group v-model="form.paddedMethod">
                <el-radio label="L">左补齐</el-radio>
                <el-radio label="R">右补齐</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <!--横线组件纯纯为了页面好看-->
      <el-divider></el-divider>
      <el-row style="margin-bottom: 20px;">
        <el-col :span="1.5">
          <div style="font-size: 25px; margin-top: 5px">规则明细</div>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" @click="handleAddPart" style="margin-left: 20px;">新增</el-button>
        </el-col>
      </el-row>
      <el-table ref="partTable" :data="partList">
        <el-table-column prop="partIndex" label="序号" align="center"></el-table-column>
        <el-table-column prop="partLength" label="长度" align="center"></el-table-column>
        <el-table-column prop="partType" label="类型" align="center">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_autocode_parttype" :value="scope.row.partType"/>
          </template>
        </el-table-column>
        <el-table-column label="值" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.partType==='FIXCHAR'">{{ scope.row.fixCharacter }}</span>
            <span v-if="scope.row.partType==='NOWDATE'">{{ scope.row.dateFormat }}</span>
            <span v-if="scope.row.partType==='INPUTCHAR'">{{ scope.row.inputCharacter }}</span>
            <span v-if="scope.row.partType==='SERIALNO'"></span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleEditPart(scope.row)">修改</el-button>
            <el-button type="danger" size="mini" @click="handleDeletePart(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--横线组件纯纯为了页面好看-->
      <el-divider></el-divider>
      <el-row style="margin-bottom: 20px;">
        <el-col :span="1.5">
          <div style="font-size: 25px; margin-top: 5px">关联产品</div>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" @click="handleAddProduct" style="margin-left: 20px;">新增</el-button>
        </el-col>
      </el-row>
      <el-table ref="productTable" :data="productList">
        <el-table-column prop="itemCode" label="产品编码" align="center"/>
        <el-table-column prop="itemName" label="产名称" align="center"/>
        <el-table-column prop="specification" label="规格型号" align="center"/>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="handleDeleteProduct(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改规则组成对话框 -->
    <el-dialog :title="partTitle" :visible.sync="partOpen" width="900px" append-to-body>
      <el-form ref="partForm" :model="partForm" :inline="true" :rules="partRules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="分段编码" prop="partCode">
              <el-input v-model="partForm.partCode" placeholder="请输入分段编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分段名称" prop="partName">
              <el-input v-model="partForm.partName" placeholder="请输入分段名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分段序号" prop="partIndex">
              <el-input-number v-model="partForm.partIndex" placeholder="请输入分段序号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分段长度" prop="partLength">
              <el-input-number v-model="partForm.partLength" placeholder="请输入分段长度"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分段类型" prop="partType">
              <el-select v-model="partForm.partType">
                <el-option
                  v-for="item in dict.type.sys_autocode_parttype"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="日期时间格式" prop="dateFormat" v-if="partForm.partType=='NOWDATE'">
              <el-input v-model="partForm.dateFormat" placeholder="请输入日期时间格式"/>
            </el-form-item>

            <el-form-item label="输入字符" prop="inputCharacter" v-if="partForm.partType=='INPUTCHAR'">
              <el-input v-model="partForm.inputCharacter" placeholder="请填写输入字符"/>
            </el-form-item>

            <el-form-item label="固定字符" prop="fixCharacter" v-if="partForm.partType=='FIXCHAR'">
              <el-input v-model="partForm.fixCharacter" placeholder="请填写固定字符"/>
            </el-form-item>

            <el-form-item label="起始流水号" prop="seriaStartNo" v-if="partForm.partType=='SERIALNO'">
              <el-input-number v-model="partForm.seriaStartNo" placeholder="请填写起始流水号"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="流水号步长" prop="seriaStep" v-if="partForm.partType=='SERIALNO'">
              <el-input-number v-model="partForm.seriaStep" placeholder="请填写流水号步长"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否循环" prop="cycleFlag" v-if="partForm.partType=='SERIALNO'">
              <el-radio-group v-model="partForm.cycleFlag">
                <el-radio label="Y">是</el-radio>
                <el-radio label="N">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="循环方式" prop="cycleMethod"
                          v-if="partForm.partType =='SERIALNO' && partForm.cycleFlag =='Y'">
              <el-select v-model="partForm.cycleMethod">
                <el-option
                  v-for="item in dict.type.sys_autocode_cyclemethod"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="partForm.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="savePartForm">确 定</el-button>
        <el-button @click="cancelPart">取 消</el-button>
      </div>
    </el-dialog>
    <mdItemSingle ref="mdItemSingle" :itemOrProduct="'PRODUCT'" @onSelected="handleMdItemSingle"></mdItemSingle>
    <el-dialog title="展示条码" :visible.sync="open1" width="80%" append-to-body>
      <div>


        <barcode :value="item" v-for="item in barcodeValue" :text="'产品'"></barcode>


      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open1=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listRule, getRule, delRule, addRule, updateRule} from "@/api/mes/md/barCodeRule";
import {genCode} from "@/api/system/autocode/rule"
import MdItemSingle from "@/components/itemSelect/single.vue"
import Barcode from 'vue-barcode';

export default {
  name: "BarCodeRule",
  dicts: ['sys_yes_no', 'sys_autocode_cyclemethod', 'sys_autocode_parttype'],
  components: {
    MdItemSingle,
    Barcode
  },
  data() {
    return {
      barcodeValue: ['bar202505200001', 'bar202505200002', 'bar202505200003', 'bar202505200004', 'bar202505200005'],
      // 遮罩层
      loading: true,
      title: '',
      partTitle: '',
      optType: 'add',
      autoGenFlag: false,
      // 选中数组
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 条码生成规则表格数据
      ruleList: [],
      //绑定产品列表
      productList: [],
      //规则组成列表
      partList: [],
      // 弹出层标题
      // 是否显示弹出层
      open: false,
      open1: false,
      partOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleCode: null,
        ruleName: null,
        ruleDesc: null,
        maxLength: null,
        isPadded: null,
        paddedChar: null,
        paddedMethod: null,
        enableFlag: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
      },
      // 表单参数
      form: {},
      partForm: {},
      // 表单校验
      rules: {
        ruleCode: [
          {required: true, message: "规则编码不能为空", trigger: "blur"}
        ],
        ruleName: [
          {required: true, message: "规则名称不能为空", trigger: "blur"}
        ],
        isPadded: [
          {required: true, message: "是否补齐不能为空", trigger: "blur"}
        ],
        enableFlag: [
          {required: true, message: "是否启用不能为空", trigger: "blur"}
        ],
      },
      partRules: {
        partCode: [
          {required: true, message: "组成编码不能为空", trigger: "blur"}
        ],
        partName: [
          {required: true, message: "组成名称不能为空", trigger: "blur"}
        ],
        partIndex: [
          {required: true, message: "组成序号不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询条码生成规则列表 */
    getList() {
      this.loading = true;
      listRule(this.queryParams).then(response => {
        this.ruleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ruleId: null,
        ruleCode: null,
        ruleName: null,
        ruleDesc: null,
        maxLength: null,
        isPadded: null,
        paddedChar: null,
        paddedMethod: null,
        enableFlag: null,
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        tenantId: null
      };
      this.resetForm("form");
      this.partList = [];
      this.productList = [];
      this.autoGenFlag = false;
    },
    resetPartForm() {
      this.partForm = {
        partIndex: 0,
        partType: undefined,
        partCode: undefined,
        partName: undefined,
        partLength: 0,
        dateFormat: undefined,
        inputCharacter: undefined,
        fixCharacter: undefined,
        seriaStartNo: undefined,
        seriaStep: undefined,
        seriaNowNo: undefined,
        cycleFlag: undefined,
        cycleMethod: undefined,
        remark: undefined
      };
      this.resetForm("partForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.optType = 'add'
      this.open = true;
      this.title = "新增";
      this.handleAutoGenChange(true);
    },
    handleDYTM() {
      this.open1 = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.optType = 'update'
      this.open = true;
      this.title = "修改";
      getRule(row.ruleId).then(response => {
        this.form = response.data;
        this.partList = response.data.mdBarCodePartList;
        this.productList = response.data.mdBarCodeItemList;
      });
    },
    handleAddPart() {
      this.resetPartForm();
      this.partOpen = true;
      this.partTitle = '新增规则组成';
    },
    handleEditPart(row) {
      this.resetPartForm();
      this.partOpen = true;
      this.partTitle = '修改规则组成';
      this.partForm = row;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.mdBarCodeItemList = this.productList;
          this.form.mdBarCodePartList = this.partList;
          if (this.form.ruleId != null) {
            updateRule(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRule(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ruleIds = row.ruleId || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + row.ruleCode + '"的条码规则？').then(function () {
        return delRule(ruleIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    switchChange(row) {
      let text = row.enableFlag === 'Y' ? '禁用' : '启用';
      this.$modal.confirm('是否确认' + text + '编号为"' + row.ruleCode + '"的规则？')
      updateRule({ruleId: row.ruleId, enableFlag: row.enableFlag}).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      })
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode('BAR_RULE_CODE').then(response => {
          this.form.ruleCode = response;
        });
      } else {
        this.form.ruleCode = null;
      }
    },
    savePartForm: function () {
      this.$refs["partForm"].validate(valid => {
        if (valid) {
          const data = {
            partIndex: this.partForm.partIndex,
            partType: this.partForm.partType,
            partCode: this.partForm.partCode,
            partName: this.partForm.partName,
            partLength: this.partForm.partLength,
            dateFormat: this.partForm.dateFormat,
            inputCharacter: this.partForm.inputCharacter,
            fixCharacter: this.partForm.fixCharacter,
            seriaStartNo: this.partForm.seriaStartNo,
            seriaStep: this.partForm.seriaStep,
            seriaNowNo: this.partForm.seriaNowNo,
            cycleFlag: this.partForm.cycleFlag,
            cycleMethod: this.partForm.cycleMethod
          }
          const index = this.partList.findIndex(item => item.partIndex == data.partIndex);
          if (index != -1) {
            this.partList.splice(index, 1);
            this.partList.splice(index, 0, data);
          } else {
            this.partList.push(data);
          }
          this.partOpen = false;
          this.resetPartForm();
        }
      });
    },
    cancelPart() {
      this.partOpen = false;
    },
    handleDeletePart(row) {
      this.partList.splice(this.partList.indexOf(row), 1);
    },
    handleAddProduct() {
      this.$refs.mdItemSingle.showFlag = true;
    },
    handleMdItemSingle(data) {
      const index = this.productList.findIndex(item => item.itemCode == data.itemCode);
      if (index === -1) {
        this.productList.push(data);
      }
    },
    handleDeleteProduct(row) {
      this.productList.splice(this.productList.findIndex(item => item.itemCode == row.itemCode), 1);
    }
    /** 导出按钮操作 */
    /*handleExport() {
      this.download('md/rule/export', {
        ...this.queryParams
      }, `rule_${new Date().getTime()}.xlsx`)
    }*/
  }
};
</script>
